#include "pcbDetectCtx.h"

// 初始化静态成员
PCBDetectionContext* PCBDetectionContext::instance = nullptr;
std::mutex PCBDetectionContext::mtx;

// 私有辅助方法：检查架子是否已满
bool PCBDetectionContext::isRackFull(const RackInfo& rack) const {
    return rack.occupiedCount >= 16;
}

// 私有辅助方法：查找空槽位
int PCBDetectionContext::findEmptySlot(const RackInfo& rack) const {
    for (int i = 0; i < 16; i++) {
        std::cout << "i = " << i << std::endl;
        std::cout << "rack.slots[i] = " << rack.slots[i] << std::endl;
        if (!rack.slots[i]) {
            return i;
        }
    }
    return -1; // 没有空槽位
}

// 构造函数实现
PCBDetectionContext::PCBDetectionContext() 
    : enabledDefects(0),
      deviceStatus(DeviceStatus::PAUSED) {
    // 初始化当前好架子
    currentGoodRack.rackId = 0;
    currentGoodRack.slots.reset();
    currentGoodRack.occupiedCount = 0;
    
    // 初始化当前坏架子
    currentBadRack.rackId = 0;
    currentBadRack.slots.reset();
    currentBadRack.occupiedCount = 0;

    productInfo.model="";     
    productInfo.batch="";    
    productInfo.serial="";  
    productInfo.serialCounter = 0;       // 序列号计数器

}

// 获取单例实例
PCBDetectionContext* PCBDetectionContext::getInstance() {
    std::lock_guard<std::mutex> lock(mtx);
    if (instance == nullptr) {
        instance = new PCBDetectionContext();
    }
    return instance;
}

// 释放单例实例
void PCBDetectionContext::releaseInstance() {
    std::lock_guard<std::mutex> lock(mtx);
    if (instance != nullptr) {
        delete instance;
        instance = nullptr;
    }
}

// 3. 架子和槽位管理方法实现
RackSlotInfo PCBDetectionContext::getAvailableGoodRackSlot(bool placePCB) {
    int slotId = findEmptySlot(currentGoodRack);
    std::cout << "findEmptySlot = " << slotId << std::endl;
    if (slotId != -1) {
        if (placePCB) {
            currentGoodRack.slots.set(slotId, true);
             std::cout << "currentGoodRack.slots[i] = " << currentGoodRack.slots[slotId] << std::endl;
            currentGoodRack.occupiedCount++;
        }
        return {currentGoodRack.rackId, slotId, true};
    }
    
    // 当前架子已满
    return { -1, -1, false };
}

RackSlotInfo PCBDetectionContext::getAvailableBadRackSlot(bool placePCB) {
    int slotId = findEmptySlot(currentBadRack);
    if (slotId != -1) {
        if (placePCB) {
            currentBadRack.slots.set(slotId, true);
            currentBadRack.occupiedCount++;
        }
        return {currentBadRack.rackId, slotId, true};
    }
    
    // 当前架子已满
    return { -1, -1, false };
}

void PCBDetectionContext::resetGoodRack() {
    currentGoodRack.slots.reset();
    currentGoodRack.occupiedCount = 0;
}

void PCBDetectionContext::resetBadRack() {
    currentBadRack.slots.reset();
    currentBadRack.occupiedCount = 0;
}

std::string PCBDetectionContext::getGoodRackStatus() const {
    std::string result = "好的PCB架子 " + std::to_string(currentGoodRack.rackId) + " 状态:\n";
    result += "  已占用: " + std::to_string(currentGoodRack.occupiedCount) + "/16\n";
    result += "  占用槽位: ";
    
    for (int i = 0; i < 16; i++) {
        if (currentGoodRack.slots[i]) {
            result += std::to_string(i) + ", ";
        }
    }
    
    if (!result.empty() && result.find("占用槽位: ") != std::string::npos) {
        result = result.substr(0, result.length() - 2); // 移除最后的逗号和空格
    }
    
    return result;
}

std::string PCBDetectionContext::getBadRackStatus() const {
    std::string result = "坏的PCB架子 " + std::to_string(currentBadRack.rackId) + " 状态:\n";
    result += "  已占用: " + std::to_string(currentBadRack.occupiedCount) + "/16\n";
    result += "  占用槽位: ";
    
    for (int i = 0; i < 16; i++) {
        if (currentBadRack.slots[i]) {
            result += std::to_string(i) + ", ";
        }
    }
    
    if (!result.empty() && result.find("占用槽位: ") != std::string::npos) {
        result = result.substr(0, result.length() - 2); // 移除最后的逗号和空格
    }
    
    return result;
}

// 4. 设备状态管理方法实现
void PCBDetectionContext::setDeviceStatus(DeviceStatus status) {
    deviceStatus = status;
}

DeviceStatus PCBDetectionContext::getDeviceStatus() const {
    return deviceStatus;
}

std::string PCBDetectionContext::getDeviceStatusString() const {
    switch (deviceStatus) {
        case DeviceStatus::STOPPED:
            return "停止";
        case DeviceStatus::RUNNING:
            return "运行";
        case DeviceStatus::PAUSED:
            return "暂停";
        default:
            return "未知";
    }
}

// 打印当前上下文状态
void PCBDetectionContext::printStatus() const {
    std::cout << "PCB检测上下文状态:" << std::endl;
    
    // 打印启用的缺陷类型
    std::cout << "启用的缺陷类型: " << getEnabledDefects() << std::endl;
    
    // 打印架子状态
    std::cout << getGoodRackStatus() << std::endl;
    std::cout << getBadRackStatus() << std::endl;
    
    // 打印设备状态
    std::cout << "设备状态: " << getDeviceStatusString() << std::endl;
}

// 1. 缺陷类型管理方法实现
void PCBDetectionContext::enableDefect(DefectType type) {
    enabledDefects.set(static_cast<size_t>(type), true);
}

void PCBDetectionContext::disableDefect(DefectType type) {
    enabledDefects.set(static_cast<size_t>(type), false);
}

bool PCBDetectionContext::isDefectEnabled(DefectType type) const {
    return enabledDefects[static_cast<size_t>(type)];
}

std::string PCBDetectionContext::getEnabledDefects() const {
    std::string result = "";
    for (size_t i = 0; i < 8; i++) {
        if (enabledDefects[i]) {
            switch (static_cast<DefectType>(i)) {
                case DefectType::MISSING_HOLE:
                    result += "漏孔, ";
                    break;
                case DefectType::MOUSE_BITE:
                    result += "鼠咬, ";
                    break;
                case DefectType::OPEN_CIRCUIT:
                    result += "开路, ";
                    break;
                case DefectType::SHORT:
                    result += "短路, ";
                    break;
                case DefectType::SPUR:
                    result += "毛刺, ";
                    break;
                case DefectType::SPURIOUS_COPPER:
                    result += "杂铜, ";
                    break;
                case DefectType::PINHOLE:
                    result += "针孔, ";
                    break;
                case DefectType::SCRATCH:
                    result += "划痕, ";
                    break;
            }
        }
    }
    
    if (!result.empty()) {
        result = result.substr(0, result.length() - 2); // 移除最后的逗号和空格
    }
    
    return result;
}

/**
 * 从控制消息更新上下文状态
 * @param message 控制消息
 */
void PCBDetectionContext::updateFromControlMessage(const ControlMessage& message) {
    // 1. 更新启用的缺陷类型
    enabledDefects.reset(); // 先清空所有启用的缺陷类型
    for (const auto& defect : message.defectTypes) {
        enableDefect(defect); // 逐个启用消息中指定的缺陷类型
    }
    
    // 2. 更新设备状态
    switch (message.action) {
        case ControlAction::START:
            setDeviceStatus(DeviceStatus::RUNNING);
            break;
        case ControlAction::STOP:
            setDeviceStatus(DeviceStatus::STOPPED);
            break;
        case ControlAction::PAUSE:
            setDeviceStatus(DeviceStatus::PAUSED);
            break;
        default:
            // 默认保持当前状态
            break;
    }

        // 3. 新增：更新产品信息
    productInfo.model = message.productInfo.model;
    productInfo.batch = message.productInfo.batch;
    productInfo.serial = message.productInfo.serial;
}

// 5. 产品信息管理方法实现
ProductInfo PCBDetectionContext::getProductInfo() {
    // 生成格式如 "PCB202507060001" 的序列号
    int counter = productInfo.serialCounter.fetch_add(1);
    std::string serial = productInfo.serial + 
                         std::to_string(counter + 1); // +1因为counter从0开始
    
    return {
        productInfo.model,
        productInfo.batch,
        serial
    };
}